import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import Sequential, Linear, ReLU
from torch_geometric.nn import GINConv, global_add_pool
from torch.autograd import Variable
from torch_geometric.nn import global_mean_pool as gap, global_max_pool as gmp


"""
不修改protein的conv1d
直接计算

=因为原本是仅保留整个蛋白质序列中的一个有效氨基酸特征向量，
要权重的话就必须保存所有氨基酸的特征向量，
所以1）不能转置，1000维不能减少
再2）在池化层之前加入权重计算
"""


# GINConv model
class GINConvNet(torch.nn.Module):
    def __init__(self, n_output=1,num_features_xd=78, num_features_xt=25,
                 n_filters=32, embed_dim=128, output_dim=128, dropout=0.2):

        super(GINConvNet, self).__init__()

        dim = 32
        self.dropout = nn.Dropout(dropout)
        self.relu = nn.ReLU()
        self.n_output = n_output
        # convolution layers
        nn1 = Sequential(Linear(num_features_xd, dim), ReLU(), Linear(dim, dim))
        self.conv1 = GINConv(nn1)
        self.bn1 = torch.nn.BatchNorm1d(dim)

        nn2 = Sequential(Linear(dim, dim), ReLU(), Linear(dim, dim))
        self.conv2 = GINConv(nn2)
        self.bn2 = torch.nn.BatchNorm1d(dim)

        nn3 = Sequential(Linear(dim, dim), ReLU(), Linear(dim, dim))
        self.conv3 = GINConv(nn3)
        self.bn3 = torch.nn.BatchNorm1d(dim)

        nn4 = Sequential(Linear(dim, dim), ReLU(), Linear(dim, dim))
        self.conv4 = GINConv(nn4)
        self.bn4 = torch.nn.BatchNorm1d(dim)

        nn5 = Sequential(Linear(dim, dim), ReLU(), Linear(dim, dim))
        self.conv5 = GINConv(nn5)
        self.bn5 = torch.nn.BatchNorm1d(dim)

        self.fc1_xd = Linear(dim, output_dim)

        # 1D convolution on protein sequence
        # n_filters = 32
        self.embedding_xt = nn.Embedding(num_features_xt + 1, embed_dim)
        self.conv_xt_1 = nn.Conv1d(in_channels=128, out_channels=n_filters, kernel_size=8)
        self.fc1_xt = nn.Linear(96*107, output_dim)

        # combined layers
        self.fc1 = nn.Linear(256, 1024)
        self.fc2 = nn.Linear(1024, 1024)
        self.fc3 = nn.Linear(1024, 256)
        self.out = nn.Linear(256, self.n_output)        # n_output = 1 for regression task

        """最后一层输出Dense,采用sigmoid激活"""
        self.sigmoid = nn.Sigmoid()
        self.bn_t1 = torch.nn.BatchNorm1d(n_filters)
        self.conv_xt_2 = nn.Conv1d(in_channels=n_filters, out_channels=n_filters*2, kernel_size=8)
        self.bn_t2 = torch.nn.BatchNorm1d(n_filters*2)
        self.conv_xt_3 = nn.Conv1d(in_channels=n_filters*2, out_channels=n_filters*3, kernel_size=8)
        self.bn_t3 = torch.nn.BatchNorm1d(n_filters*3)
        self.conv_xt_4 = nn.Conv1d(in_channels=n_filters * 3, out_channels=n_filters * 4, kernel_size=8)
        self.bn_t4 = torch.nn.BatchNorm1d(n_filters * 4)

        self.global_max_pooling = nn.AdaptiveMaxPool1d(1)

        self.W_attention = nn.Linear(n_filters * 4,n_filters * 4)

    def forward(self, data):
        x, edge_index, batch = data.x, data.edge_index, data.batch
        target = data.target

        x = F.relu(self.conv1(x, edge_index))
        x = self.bn1(x)
        x = F.relu(self.conv2(x, edge_index))
        x = self.bn2(x)
        x = F.relu(self.conv3(x, edge_index))
        x = self.bn3(x)
        x = F.relu(self.conv4(x, edge_index))
        x = self.bn4(x)
        x = F.relu(self.conv5(x, edge_index))
        x = self.bn5(x)
        x = global_add_pool(x, batch)
        x = F.relu(self.fc1_xd(x))
        x = F.dropout(x, p=0.2, training=self.training)
        print(x.shape)

        """
        输出每层的shape
        keras的输入输出是（None,steps,channels）,channels=in_channels=n_filters
        pytorch不会是（None,channels,steps）吧？！
        """
        #protein
        # print('strat==============')
        embedded_xt = self.embedding_xt(target)
        # print(embedded_xt.shape)

        # embedded_xt = embedded_xt.transpose(1, 2).contiguous()
        # print(embedded_xt.shape)

        conv_xt = self.conv_xt_1(embedded_xt)
        conv_xt=self.bn_t1(conv_xt)
        conv_xt=self.relu(conv_xt)
        # print(conv_xt.shape)

        conv_xt=self.conv_xt_2(conv_xt)
        conv_xt = self.bn_t2(conv_xt)
        conv_xt=self.relu(conv_xt)
        # print(conv_xt.shape)

        conv_xt=self.conv_xt_3(conv_xt)
        conv_xt = self.bn_t3(conv_xt)
        conv_xt = self.relu(conv_xt)
        # print(conv_xt.shape)

        conv_xt = self.conv_xt_4(conv_xt)
        conv_xt = self.bn_t4(conv_xt)
        conv_xt = self.relu(conv_xt)
        # print(conv_xt.shape)


        #权重计算——一维卷积的变动毫无意义啊，暂时放弃
        ws=[[[]]]
        wx=torch.unsqueeze(x, 1) #drug从[16，128]扩充为[16，1，128]
        for i in range(list(conv_xt.size())[0]):
            h = torch.relu(self.W_attention(wx[i]))
            hs = torch.relu(self.W_attention(conv_xt[i]))
            weights = torch.tanh(F.linear(h, hs))
            ys = torch.t(weights) * hs
            ws.append(torch.mean(ys, 0)) #把第一维数据完整加入ws的第一维
        conv_xt=ws

        #global max pooling
        # t_in=conv_xt.transpose(1, 2).contiguous()
        conv_xt= self.global_max_pooling(conv_xt)   #mean?
        # print(conv_xt.shape)
        # conv_xt=conv_xt.transpose(1, 2).contiguous()
        # print(conv_xt.shape)
        # flatten
        # xt = conv_xt.view(-1, 96*107)
        xt = conv_xt.view(-1, 128)  #为第4层conv准备，如果不加第4层conv,则为（-1，96），就需要fc1_xt去改，扩充不太好感觉
        # xt = self.fc1_xt(xt)
        print(xt.shape)
        #输出128位
        # print('end==============')



        # concat
        xc = torch.cat((x, xt), 1)
        # add some dense layers
        xc = self.fc1(xc)
        xc = self.relu(xc)
        xc = self.dropout(xc)
        xc = self.fc2(xc)
        xc = self.relu(xc)
        xc = self.dropout(xc)
        xc = self.fc3(xc)
        xc = self.relu(xc)
        xc = self.dropout(xc)

        out = self.out(xc)

        out=self.sigmoid(out)
        return out
